package com.youme.section.login.sms

import android.view.View
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import com.salton123.ui.base.YoumeBaseFragment
import com.hjq.toast.ToastUtils
import com.hyphenate.easeim.BuildConfig
import com.hyphenate.easeim.R
import com.youme.RouterManager
import com.youme.base.Ret
import com.youme.util.Utils.isNetworkDisconnect
import com.youme.viewmodel.YouMeApiViewModel
import kotlinx.android.synthetic.main.youme_fragment_login_step_one.*
import kotlinx.coroutines.launch

/**
 * @Time:2021/3/26 17:06
 * @Author:wujinsheng
 * @Description:
 */
class YouMeSmsLoginStepOneFragment(var viewModel: YouMeApiViewModel) : YoumeBaseFragment() {
    override fun getLayoutId(): Int = R.layout.youme_fragment_login_step_one

    var phoneNumber = ""
        get() = etPhoneNumber.text.toString()
    private val mStepTwo by lazy {
        YouMeSmsLoginStepTwoFragment(phoneNumber, viewModel)
    }

    override fun initViewAndData() {
        setCountdownSetting()
        etPhoneNumber.doAfterTextChanged {
            if (it.isNullOrBlank()) {
                btnVerifyCode.isEnabled = false
                btnVerifyCode.background = resources.getDrawable(R.drawable.youme_login_et_bg_disabled)
            } else {
                btnVerifyCode.isEnabled = true
                btnVerifyCode.background = resources.getDrawable(R.drawable.youme_login_et_bg)
            }
        }
        if (BuildConfig.APP_DEVELOP) {
            etPhoneNumber.setText("18688367977")
        }
        setListener(ivAlipayLogin, ivWechatLogin, tvGoRegister)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v) {
            ivAlipayLogin -> {
                ToastUtils.show("阿里支付登录")
            }
            ivWechatLogin -> {
                ToastUtils.show("微信登录")
            }
            tvGoRegister -> {
                RouterManager.register(requireActivity())
            }
        }
    }

    private fun setCountdownSetting() {
        btnVerifyCode.setOnClickListener {
            lifecycleScope.launch {
                if (isNetworkDisconnect(context)) {
                    ToastUtils.show("网络异常")
                } else {
                    if (!BuildConfig.APP_DEVELOP) {
                        viewModel.loginCode(phoneNumber).also {
                            if (it is Ret.Success) {
                                etPhoneNumber.isFocusable = true
                                etPhoneNumber.requestFocus()
                                start(mStepTwo)
                            } else if (it is Ret.Failure) {
                                ToastUtils.show(it.errorMessage)
                            }
                        }
                    } else {
                        start(mStepTwo)
                    }
                }
            }
        }
    }
}